{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "collapsed_sections": [
        "dm-qqTdZDUlZ",
        "GGKgsW5gvAuf",
        "0CqpJGR6ecYW"
      ],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pEYsuj0J9pId"
      },
      "outputs": [],
      "source": [
        "\"\"\"\n",
        "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
        "\n",
        "Instructions for setting up Colab are as follows:\n",
        "1. Open a new Python 3 notebook.\n",
        "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GitHub\" tab -> copy/paste GitHub URL)\n",
        "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
        "4. Run this cell to set up dependencies.\n",
        "5. Restart the runtime (Runtime -> Restart Runtime) for any upgraded packages to take effect\n",
        "\n\nNOTE: User is responsible for checking the content of datasets and the applicable licenses and determining if suitable for the intended use.\n",
        "\"\"\"\n",
        "# If you're using Google Colab and not running locally, run this cell.\n",
        "import os\n",
        "\n",
        "# Install dependencies\n",
        "!pip install wget\n",
        "!apt-get install sox libsndfile1 ffmpeg\n",
        "!pip install text-unidecode\n",
        "!pip install matplotlib>=3.3.2\n",
        "\n",
        "## Install NeMo\n",
        "BRANCH = 'main'\n",
        "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n",
        "\n",
        "## Grab the config we'll use in this example\n",
        "# !mkdir configs\n",
        "# !wget -P configs/ https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/examples/asr/conf/contextnet_rnnt/contextnet_rnnt.yaml"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# ASR Domain Adaptation with Adapters\n",
        "\n",
        "Throughout various Automatic Speech Recognition tutorials, you may have noticed that ASR datasets are generally enormous - on the order of hundreds or even thousands of hours of speech. Such a large amount of data imposes significant restrictions on the development of ASR models due to the cost of collection of labeled data (or even unlabeled datasets) and the severe compute cost to train a model on that much data. \n",
        "\n",
        "We further see that when fine-tuning a pre-trained model, we need large datasets and compute to achieve superior results and avoid overfitting to the new dataset. Worse, by training the entire model (or even just the decoder modules), we severely degrade the model's performance on the original dataset.\n",
        "\n",
        "-----\n",
        "\n",
        "In this tutorial, we will showcase **Adapters** : A powerful method to efficiently adapt a pre-trained model to a new dataset (with minimal amounts of data, even just 30 minutes !) with minimal compute resources (on a single GPU, in around 10 minutes of training time).\n"
      ],
      "metadata": {
        "id": "cTV4WLrArmxS"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## What are Adapters?\n",
        "\n",
        "Adapters are a straightforward concept proposed in multiple papers across various domains. For the sake of brevity, we will choose a recent paper [Using Adapters to Overcome Catastrophic Forgetting in End-to-End Automatic Speech Recognition](https://arxiv.org/abs/2203.16082) as a reference for this discussion.\n",
        "\n",
        "Essentially, an **Adapter** is any **trainable module that is added * after * a model has been trained to convergence**. \n",
        "\n",
        "- These additional modules form a residual bridge over the output of each layer they adapt, such that the model's original performance is not lost. \n",
        "- The original parameters of the model are frozen in their entirety - so that we don't lose performance on the original domain.\n",
        "- We train only the new adapter parameters (an insignificant fraction of the total number of parameters). This allows fast experimentation.\n",
        "\n",
        "-----\n",
        "\n",
        "Adapters are a straightforward concept - as shown by the diagram below. At their simplest, they are residual Feedforward layers that compress the input dimension ($D$) to a small bottleneck dimension ($H$), such that $R^D \\text{->} R^H$, compute an activation (such as ReLU), finally mapping $R^H \\text{->} R^D$ with another Feedforward layer. This output is then added to the input via a simple residual connection.\n",
        "\n",
        "<div align=\"center\">\n",
        "  <img src=\"https://mermaid.ink/img/pako:eNptkLFqwzAQhl9F3ORAPDSjA4EUx6RgXEjbycpwWOdG1JaMfEoakrx7ZcfpUKrlxH_fz4d0gcoqggTqxp6qAzoW76k0Ipx1-WI6z3sRxyuRF1GOZ3KisK6d3YG8GFdZ9hRJeLbMDRmqvkRGpDLrTuiUiEWUigBtlyIVqzBnEqZ66I39dcX6iKytKXeUf-wn-286QoFeBMvmu0PTD-EfyXaQpP9JFmP_1XN4S3kfD8W4ue6o18pjc52gYQlzaMm1qFX4msuQSOADtSQhCdfaOupZgjS3QPpOIdNGabYOkhqbnuaAnu3b2VSQsPP0gFKNnw7bibr9AJkZdXU\" height=100% />\n",
        "</div>\n",
        "\n",
        "-----\n",
        "\n",
        "Adapter modules such as this are usually initialized. The initial output of the adapter will always be zeros to prevent degradation of the original model's performance due to the addition of such modules."
      ],
      "metadata": {
        "id": "f-LSGyL4xw9c"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Advantages of Adapters\n",
        "\n",
        "Since adapters are additional parameters added to an already trained network, and due to their construction, they possess multiple beneficial properties.\n",
        "\n",
        "- **Added parameter cost**: They cost an insignificant number of parameters compared to the original model (generally 0.5% - 1% of the initial parameter count).\n",
        "- **Residual bridge**: Adapters are initialized with special care, such that their contribution to the output of each layer they adapt is initially 0. Therefore, after the addition of the adapters, the original model does not lose any accuracy at all (even without training the adapters).\n",
        "- **Fast convergence**: Since the adapters only need to learn to modify the module's output slightly, and each adapter has a trivial parameter cost, they converge rapidly.\n",
        "- **Adapt only the encoder**: Adapters can be used anywhere, but they are most commonly used in just the encoder, keeping the decoder modules frozen. This allows the decoder to be unaffected by costly CTC/RNN-T training, which takes time to converge, and just the adapter modules in the encoder need to be updated.\n",
        "- **Dynamic and flexible adaptation**: Since adapter modules can be added any number of times, a single shared \"core\" model can have multiple adapters that are enabled/disabled dynamically to adapt to numerous scenarios. This potentially offers the case where a single \"core\" model is shared across multiple users, and each user has a small, personal adapter module used for personalization.  "
      ],
      "metadata": {
        "id": "YGn1__-Jv2Bq"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Limitations of Adapters\n",
        "\n",
        "With all those benefits, Adapters have significant drawbacks stemming from how they are currently used.\n",
        "\n",
        "Note that there is ongoing research to overcome such restrictions, which we hope to incorporate eventually.\n",
        "\n",
        "- **Frozen decoder modules**: Since the decoder is frozen to avoid forgetting the past training, it does not learn the semantics of the text from the new domain. This may hamper some models more than others.\n",
        "- **Frozen tokenization/decoding**: A consequence of the frozen decoder is that we cannot change the vocabulary (or tokenizer) of the decoder layer - as this would cause the model to forget its past training entirely. This also means that **adapters cannot be used to train in a different language than the original language**. The text of the new domain must be supported by the original model's tokenizer/decoder.\n",
        "  - **Note**: There is nothing fundamentally wrong with still changing the vocabulary of a model that supports adapters. The benefits of adapters will reduce significantly and require costly training (similar in time and memory to finetuning). The model can no longer recover its performance by disabling all of its adapters.\n",
        "- **Easy to overfit**: Since adapters enable domain adaptation on very small amounts of speech data, it is trivial to rapidly overfit these datasets and significantly degrade performance on the original domain. \n",
        "  - **Note**: This can be overcome with some experimentation, further boosted by the fast experimentation cycle that adapters enable."
      ],
      "metadata": {
        "id": "8d7y1cygv4MP"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Dataset preparation\n",
        "\n",
        "Now that we understand what adapters are and their benefits/drawbacks, we can explore how to set up adapters in NeMo ASR models.\n",
        "\n",
        "-----\n",
        "\n",
        "First, we prepare some datasets that the original model was **not trained on**, making it a new domain to be adapted. \n",
        "\n",
        "In this tutorial, we will be utilizing the `AN4` dataset - also known as the Alphanumeric dataset, which was collected and published by Carnegie Mellon University. We chose this dataset primarily because it is **very small in size** (`<1 hours of training data`), **easy to overfit when training from scratch / fine-tuning by changing the decoder** (`previous tutorials can mostly get around 10-20% WER with fine-tuning without hyperparameter tuning`), and its **text is perfectly supported by the tokenization/decoding scheme of the model**."
      ],
      "metadata": {
        "id": "mtYWTi0irkS6"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "\n",
        "if not os.path.exists(\"scripts/\"):\n",
        "  os.makedirs(\"scripts\")\n",
        "\n",
        "if not os.path.exists(\"scripts/process_an4_data.py\"):\n",
        "  !wget -P scripts/ https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/scripts/dataset_processing/process_an4_data.py"
      ],
      "metadata": {
        "id": "NpKgT6q5-gNk"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import wget\n",
        "import tarfile \n",
        "import subprocess \n",
        "import glob\n",
        "\n",
        "data_dir = \"datasets\"\n",
        "\n",
        "if not os.path.exists(data_dir):\n",
        "  os.makedirs(data_dir)\n",
        "\n",
        "# Download the dataset. This will take a few moments...\n",
        "print(\"******\")\n",
        "if not os.path.exists(data_dir + '/an4_sphere.tar.gz'):\n",
        "    an4_url = 'https://dldata-public.s3.us-east-2.amazonaws.com/an4_sphere.tar.gz'\n",
        "    an4_path = wget.download(an4_url, data_dir)\n",
        "    print(f\"Dataset downloaded at: {an4_path}\")\n",
        "else:\n",
        "    print(\"Tarfile already exists.\")\n",
        "    an4_path = data_dir + '/an4_sphere.tar.gz'\n",
        "\n",
        "\n",
        "if not os.path.exists(data_dir + '/an4/'):\n",
        "    # Untar and convert .sph to .wav (using sox)\n",
        "    tar = tarfile.open(an4_path)\n",
        "    tar.extractall(path=data_dir)\n",
        "\n",
        "    print(\"Converting .sph to .wav...\")\n",
        "    sph_list = glob.glob(data_dir + '/an4/**/*.sph', recursive=True)\n",
        "    for sph_path in sph_list:\n",
        "        wav_path = sph_path[:-4] + '.wav'\n",
        "        cmd = [\"sox\", sph_path, wav_path]\n",
        "        subprocess.run(cmd)\n",
        "\n",
        "print(\"Finished conversion.\\n******\")\n",
        "\n",
        "if os.path.exists(f\"{data_dir}/an4\"):\n",
        "  print(\"Preparing AN4 dataset ...\")\n",
        "\n",
        "  an4_path = f\"{data_dir}/\"\n",
        "  !python scripts/process_an4_data.py \\\n",
        "    --data_root=$an4_path\n",
        "\n",
        "print(\"AN4 prepared !\")"
      ],
      "metadata": {
        "id": "0wZZuUDi_gEV"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Manifest filepaths\n",
        "TRAIN_MANIFEST = os.path.join(data_dir, \"an4\", \"train_manifest.json\")\n",
        "TEST_MANIFEST = os.path.join(data_dir, \"an4\", \"test_manifest.json\")"
      ],
      "metadata": {
        "id": "9fiqQeWDAXsH"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Prepare the \"base\" model\n",
        "\n",
        "Next, we initialize a small pre-trained model with a relatively small amount of parameters to showcase the efficacy of adapters no matter the original model size.\n",
        "\n",
        "-----\n",
        "\n",
        "Most importantly, we discuss a simple way to enable Adapter specific support to a pre-trained model checkpoint - by modifying the `encoder` config before loading the model."
      ],
      "metadata": {
        "id": "q2nxi5RzAfZ5"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import torch\n",
        "from omegaconf import OmegaConf, open_dict\n",
        "from pytorch_lightning import Trainer\n",
        "\n",
        "import nemo.collections.asr as nemo_asr"
      ],
      "metadata": {
        "id": "F-wt9y5iAali"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "model_name = \"stt_en_conformer_ctc_small\""
      ],
      "metadata": {
        "id": "uVOfU7gsCI5u"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Prepare an Adapter-compatible Encoder\n",
        "\n",
        "The original model was trained without any adapters, and therefore its encoder does not support adapters.\n",
        "\n",
        " To add adapter modules to these models, we perform a few simple steps - \n",
        "\n",
        "- Extract the model config from the \"base\" model.\n",
        "- Update the `encoder` section of the config to a subclass of that model (which does have Adapter support)\n",
        "- Initialize the model with this new config, therefore enabling adapter support."
      ],
      "metadata": {
        "id": "TitUAeq67Hkl"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "- Extract just the config of the model."
      ],
      "metadata": {
        "id": "5V5UY-5c8FDv"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "cfg = nemo_asr.models.ASRModel.from_pretrained(model_name, return_config=True)"
      ],
      "metadata": {
        "id": "RzwLAHVqAqD9"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from nemo.core import adapter_mixins\n",
        "\n",
        "# Utility method to check and update the model config\n",
        "def update_model_config_to_support_adapter(model_cfg):\n",
        "    with open_dict(model_cfg):\n",
        "        adapter_metadata = adapter_mixins.get_registered_adapter(model_cfg.encoder._target_)\n",
        "        if adapter_metadata is not None:\n",
        "            model_cfg.encoder._target_ = adapter_metadata.adapter_class_path\n",
        "    \n",
        "    print(\"Updated encoder _target_ model :\", model_cfg.encoder._target_)\n",
        "    return model_cfg"
      ],
      "metadata": {
        "id": "O6xAz38-A_Bh"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "- Update the model config's `encoder` section to support Adapters."
      ],
      "metadata": {
        "id": "TDk2VMXI8OkG"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "cfg = update_model_config_to_support_adapter(cfg)"
      ],
      "metadata": {
        "id": "iyp4xUOLBi0v"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "- Finally load the model with the updated config."
      ],
      "metadata": {
        "id": "26NTK00w8VIt"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model = nemo_asr.models.ASRModel.from_pretrained(model_name, override_config_path=cfg)"
      ],
      "metadata": {
        "id": "7r36mkUGBvsy"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Next, we attach a `Trainer` to the model to be appropriately initialized.\n",
        "\n",
        "Note that we select just **300 update steps**, which is approximately just ten epochs over this dataset at batch sizes of 32. You can experiment with different steps to see the effect of overfitting or underfitting.\n",
        "\n",
        "**Recommendation**:\n",
        "\n",
        "You should normally start with 1-5 epochs of adaptation over your entire new domain, and then increase or decrease your number of training steps to trade off a balance in accuracy on general speech."
      ],
      "metadata": {
        "id": "x0C2r7388cRd"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "accelerator = 'gpu' if torch.cuda.is_available() else 'cpu'\n",
        "max_steps = 300\n",
        "\n",
        "trainer = Trainer(devices=1, accelerator=accelerator, max_steps=max_steps,\n",
        "                  enable_checkpointing=False, logger=False,\n",
        "                  log_every_n_steps=5, check_val_every_n_epoch=3)\n",
        "\n",
        "model.set_trainer(trainer)"
      ],
      "metadata": {
        "id": "sWRUXzjQMWN5"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# utility method\n",
        "import json\n",
        "from nemo.collections.asr.parts.utils.manifest_utils import read_manifest\n"
      ],
      "metadata": {
        "id": "tJBriqr3tQV7"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## [Optional] Check if the new domain is compatible with the original decoder\n",
        "\n",
        "The following section, while optional, designs a test to ensure that the text of the new domain can be adequately handled by the original decoder/tokenizer of the model. Please open each cell and execute to perform this sanity check.\n",
        "\n",
        "-----\n",
        "\n",
        "If this check fails, the training run might crash, or silently allow the model to learn to produce `⁇` tokens (when using SentencePiece tokenizers)."
      ],
      "metadata": {
        "id": "dm-qqTdZDUlZ"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Parse the base character set"
      ],
      "metadata": {
        "id": "UKTiAPV_sdFI"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "train_data = read_manifest(TRAIN_MANIFEST)\n",
        "base_sets = [set(list(sample['text'])) for sample in train_data]\n",
        "base_charset = set([])\n",
        "for charset in base_sets:\n",
        "  base_charset.update(charset)\n",
        "base_charset = list(sorted(list(base_charset)))\n",
        "\n",
        "print(\"Base charset :\", base_charset)"
      ],
      "metadata": {
        "id": "WgogR3taD7NA"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Check if there are invalid characters"
      ],
      "metadata": {
        "id": "x-0fzrfPshJj"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def check_valid_charset_in_vocab(model, charset):\n",
        "  model_vocab = model.decoder.vocabulary\n",
        "  num_invalid = 0\n",
        "\n",
        "  for char in charset:\n",
        "    if char != ' ' and char not in model_vocab:\n",
        "      print(f\"Character `{char}` does not exist in the base character set of the original model !\")\n",
        "      num_invalid += 1\n",
        "\n",
        "  print(\"Number of invalid tokens :\", num_invalid)"
      ],
      "metadata": {
        "id": "5laUkRf5Eb6l"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "check_valid_charset_in_vocab(model, base_charset)"
      ],
      "metadata": {
        "id": "5rEUqs7AFh5j"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Evaluate original performance on AN4 dev set\n",
        "\n",
        "Now that we possess a model capable of supporting adapters, let us quickly test the performance of the pre-trained model on the AN4 test set without any training or fine-tuning."
      ],
      "metadata": {
        "id": "Sf-2EHznGkI1"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "if not os.path.exists('scripts/transcribe_speech.py'):\n",
        "  !wget -P scripts/ https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/examples/asr/transcribe_speech.py\n",
        "\n",
        "if not os.path.exists('scripts/speech_to_text_eval.py'):\n",
        "  !wget -P scripts/ https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/examples/asr/speech_to_text_eval.py"
      ],
      "metadata": {
        "id": "Ak4v4aWjGoQH"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# temporarily save current model\n",
        "model.save_to(\"/content/unadapted_model.nemo\")"
      ],
      "metadata": {
        "id": "OVlBKWCiIHw7"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "The following evaluation script will properly transcribe the AN4 test set, and score it against its ground truth."
      ],
      "metadata": {
        "id": "r03iDw9k-dAm"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!python scripts/speech_to_text_eval.py \\\n",
        "  model_path=\"/content/unadapted_model.nemo\" \\\n",
        "  dataset_manifest=$TEST_MANIFEST \\\n",
        "  output_filename=\"/content/unadapted_predictions.json\" \\\n",
        "  batch_size=32 \\\n",
        "  use_cer=False"
      ],
      "metadata": {
        "id": "C6YbPt70H0-N"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "------\n",
        "\n",
        "Check the predictions of the current model"
      ],
      "metadata": {
        "id": "2VBQO3w3swu8"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!head -n 5 /content/unadapted_predictions.json"
      ],
      "metadata": {
        "id": "SE8uoRLsJA9F"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Overall, the model does quite well, obtaining roughly 6% Word Error Rate without prior training on this dataset. \n",
        "\n",
        "**Note**: Pre-trained models in NeMo are trained on several thousands of hours of speech, so it is unsurprising why this model is this accurate without any training on this toy dataset. For more realistic cases, we usually observe the range of 10-30% WER for out-of-domain speech."
      ],
      "metadata": {
        "id": "muRBgHHe-n7E"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Setup training and evaluation of the model\n",
        "\n",
        "Now that we have a baseline result, let us set up the data loaders of this model to prepare for training on this dataset.\n",
        "\n",
        "You may note: this step is nearly identical to from scratch training / fine-tuning and skips the tokenizer construction/change vocabulary steps.\n",
        "\n",
        "**Note**: Each model may have special parameters in their data loader. Please refer to the configs of the pre-trained models to determine what additional changes are necessary). Below recommendations are primarily for Conformer CTC and may differ from model to model.\n",
        "\n",
        "You can parse the model config via - `print(OmegaConf.to_yaml(model.cfg))`"
      ],
      "metadata": {
        "id": "b-L3prIzs3CW"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Setup dataloaders"
      ],
      "metadata": {
        "id": "V2WirN5KJpsD"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "with open_dict(model.cfg):\n",
        "  # Train Dataloader\n",
        "  model.cfg.train_ds.manifest_filepath = TRAIN_MANIFEST\n",
        "  model.cfg.train_ds.batch_size = 32\n",
        "  model.cfg.train_ds.is_tarred = False\n",
        "  model.cfg.train_ds.tarred_audio_filepaths = None\n",
        "\n",
        "  model.cfg.validation_ds.manifest_filepath = TEST_MANIFEST\n",
        "  model.cfg.validation_ds.batch_size = 32\n",
        "\n",
        "model.setup_training_data(model.cfg.train_ds)\n",
        "model.setup_multiple_validation_data(model.cfg.validation_ds)\n",
        "model.setup_multiple_test_data(model.cfg.validation_ds)"
      ],
      "metadata": {
        "id": "F0GIxhyCJmFv"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Setup Spectrogram Augmentation\n",
        "\n",
        "For this experiment we will continue to use the original spec augmentation config in the base model, however you may find better results by modifying the strength of this augmentation.\n",
        "\n",
        "**Note**: The script inside ASR examples **disables spec augment entirely**. This is done in order to provide a stable default to measure the best possible adaptation case, but may severely degrade the performance on general speech. Please be careful when copying the hyper parameters from the tutorial to the script for large scale experimentation."
      ],
      "metadata": {
        "id": "T3VuqcGTNuIJ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "with open_dict(model.cfg):\n",
        "  # Spec Augment\n",
        "  model.cfg.spec_augment.freq_masks = model.cfg.spec_augment.freq_masks  # Can be changed\n",
        "  model.cfg.spec_augment.freq_width = model.cfg.spec_augment.freq_width  # Can be changed\n",
        "  model.cfg.spec_augment.time_masks = model.cfg.spec_augment.time_masks  # Can be changed\n",
        "  model.cfg.spec_augment.time_width = model.cfg.spec_augment.time_width  # Can be changed\n",
        "\n",
        "model.spec_augmentation = model.from_config_dict(model.cfg.spec_augment)"
      ],
      "metadata": {
        "id": "T-XFuaA3OlOB"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Setup optimizer and scheduler\n",
        "\n",
        "An interesting thing to note for adapters is their rapid convergence speed - they do not require hundreds of thousands of update steps (though that is also possible).\n",
        "\n",
        "For this reason, we have chosen hyperparameter settings that are significantly different from other tutorials - a small learning rate multiplier of 0.1 (for NoamScheduler) and a small warmup phase of just 100 steps (remember, trainer.max_steps is just 300!).\n",
        "\n",
        "Feel free to modify these values to see the effect on adapters' convergence.\n",
        "\n",
        "**Note**: The hyper parameters below correspond to the base model and may not match those applied in the ASR examples! Please note that the script the examples defaults to an **AdamW** optimizer with a **CosineAnnealing** scheduler, where as the config of Conformers is geneally a **AdamW** optimizer with a **NoamAnnealing** scheduler. The *learning rate*, *weight decay* and other hyper parameters may not be exactly the same between the tutorial and the example scripts, so please be careful when transferring the hyper parameters for large scale experiments."
      ],
      "metadata": {
        "id": "xGpdUWl_tGuA"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "if 'optim' in model.cfg:\n",
        "  print(OmegaConf.to_yaml(model.cfg.optim))"
      ],
      "metadata": {
        "id": "UDEIfMTcP6j6"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "with open_dict(model.cfg):\n",
        "  model.cfg.optim.lr = 0.1\n",
        "  model.cfg.optim.weight_decay = 0.0\n",
        "  model.cfg.optim.sched.warmup_steps = 100\n",
        "\n",
        "model.setup_optimization(model.cfg.optim);"
      ],
      "metadata": {
        "id": "tp_8FGPcKjMd"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Adapters: Supported Components\n",
        "\n",
        "A NeMo model may have multiple types of adapters that are supported in each of their components. Let us see at a glance what are some of the adapter types supported by the Conformer ASR model.\n",
        "\n",
        "**Note**: Every domain may support their own types of adapters, and use them in different ways. Please refer to the documentation of each domain for information on the adapter support."
      ],
      "metadata": {
        "id": "AGrThAt9Qh0D"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "Let's start with the modules in which the model will support adapters. We can select these adapters with a special syntax to construct \"Module adapters\".\n",
        "\n",
        "**Note**: `''` refers to the \"default\" adapter - usually the `encoder` but it is model dependent. It may also be that no specific modules are provided, in which case only `default` adapters will be available."
      ],
      "metadata": {
        "id": "Wq1JLbNvROcL"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "if hasattr(model, 'adapter_module_names'):\n",
        "  print(model.adapter_module_names)"
      ],
      "metadata": {
        "id": "fRIDhU8RVBwi"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "Next, we can try to obtain the accepted types of each of the child modules in the Model."
      ],
      "metadata": {
        "id": "u5BOWWBjfQwN"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "for module in model.children():\n",
        "  if hasattr(module, 'get_accepted_adapter_types'):\n",
        "    types = module.get_accepted_adapter_types()\n",
        "    print(\"Module : \", module.__class__.__name__)\n",
        "\n",
        "    for tp in types:\n",
        "      print(tp)\n",
        "    print()"
      ],
      "metadata": {
        "id": "iNnSp_azQ2u8"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "As you can see, a single component of the model may support one or more adapter types (or none at all)! Below, we will experiment with the simple Linear Adapters, but as an exercise, you might try to use other adapter types present here."
      ],
      "metadata": {
        "id": "YXTC4LiSnB2O"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Adapters: Creation and Preparation\n",
        "\n",
        "Now that the data loaders have been prepared, the next step is to add the adapter modules to the model!\n",
        "\n",
        "----\n",
        "\n",
        "We first import a config for a basic `LinearAdapter` most often used in literature. \n",
        "\n",
        "`LinearAdapter` is a simple network comprising LayerNorm, a bottleneck Linear layer, an activation, and an upcast Linear layer (so that input and output channel dim match). We provide some configuration parameters (such as the input dim and the bottleneck dim)."
      ],
      "metadata": {
        "id": "WFCUrYxnGPt3"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from nemo.collections.common.parts.adapter_modules import LinearAdapterConfig"
      ],
      "metadata": {
        "id": "oZZr6vSntuyX"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "#%% [code]\n",
        "#@title Adapter Setup { display-mode: \"form\" }\n",
        "adapter_name = \"AN4\" #@param {type:\"string\"}\n",
        "adapter_dim = 32 #@param {type:\"integer\"}\n",
        "adapter_activation = \"swish\" #@param {type:\"string\"}\n",
        "adapter_norm_position = \"pre\" #@param [\"pre\", \"post\"]"
      ],
      "metadata": {
        "id": "dlj0Yud4MxOi"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "adapter_cfg = LinearAdapterConfig(\n",
        "    in_features=model.cfg.encoder.d_model,  # conformer specific model dim. Every layer emits this dim at its output.\n",
        "    dim=adapter_dim,  # the bottleneck dimension of the adapter\n",
        "    activation=adapter_activation,  # activation used in bottleneck block\n",
        "    norm_position=adapter_norm_position,  # whether to use LayerNorm at the beginning or the end of the adapter\n",
        ")\n",
        "print(adapter_cfg)"
      ],
      "metadata": {
        "id": "Uv8WRQkXU3mu"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Add a new adapter module\n",
        "\n",
        "Now that our adapter config is ready. Next, we perform a check to see what is the size of the original model and what its size will be after adding the adapter module."
      ],
      "metadata": {
        "id": "pIECyKxit58r"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.summarize()"
      ],
      "metadata": {
        "id": "-MbSTbYiYtnB"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Next, we use `add_adapter` to add adapter blocks to the `encoder`.\n",
        "\n",
        "A single line can be used to add adapter modules to every layer of the `encoder` module. We pass it a unique name to identify this adapter and the adapter config (which can be helpful to enable or disable adapters later)."
      ],
      "metadata": {
        "id": "vjYmPbwCC0LZ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.add_adapter(name=adapter_name, cfg=adapter_cfg)"
      ],
      "metadata": {
        "id": "El6ewd1GX9V7"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "As expected, the number of parameters increased by a marginal amount (roughly 200,000 parameters)."
      ],
      "metadata": {
        "id": "jMsmj1W-DTSd"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.summarize()"
      ],
      "metadata": {
        "id": "rIvw0_8iYpHW"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Enable / Disable Adapters\n",
        "\n",
        "Now that we have adapter modules, we can enable or disable them as we require. \n",
        "\n",
        "For this purpose, we utilize the `model.set_enabled_adapters` method - it takes an optional `name` and a boolean value for `enabled`. If a name is not passed, it will set enable/disable all available adapters.\n",
        "\n",
        "**Note**: We recommend training one adapter at a time, disjoint from all other adapters. As such, it simplifies the selection of adapters for each particular domain. To do so - **disable all adapters first, then enable only the newly added adapter**."
      ],
      "metadata": {
        "id": "RH6cXPW2ZHdZ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.set_enabled_adapters(enabled=False)  # disable all adapters\n",
        "model.set_enabled_adapters(name=adapter_name, enabled=True)  # enable only the current adapter we want to train"
      ],
      "metadata": {
        "id": "ogUfDkjdZKHu"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Training only the adapter(s)\n",
        "\n",
        "Now that we have enabled just the adapter we wish to adapt onto AN4 dataset, we must freeze all the other parameters of the network and train just the adapters.\n",
        "\n",
        "We provide the general utility methods for this purpose - `model.freeze()` and `model.unfreeze_enabled_adapters()`. \n",
        "\n",
        "The second method will look up all the enabled adapters selected in the previous step and enable their gradient calculation so that they can be trained."
      ],
      "metadata": {
        "id": "V87SBzdDY1x1"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.freeze()\n",
        "model.unfreeze_enabled_adapters()"
      ],
      "metadata": {
        "id": "RN2YayAoYzaI"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Why are BatchNormalization layers being frozen?\n",
        "\n",
        "A side-note here regarding BatchNormalization - even when the model is frozen, while no gradient updates will occur to the beta and gamma parameters, **the moving averages of each batch norm layer continue to update**!\n",
        "\n",
        "Such updates cause a severe issue when we disable all the adapters - while technically, no parameters of the original model were updated since the moving averages of BatchNormalization were updated. You will have degraded performance on the original domain (even with all adapters disabled !).\n",
        "\n",
        "-----\n",
        "\n",
        "For this reason, `unfreeze_enabled_adapters()` has an argument `freeze_batchnorm=True` as the default. It will find all the batch normalization layers and disable this flag so that it will the encoder layers remain exactly frozen even during adapter finetuning. This allows the original model performance to be recovered.\n",
        "\n"
      ],
      "metadata": {
        "id": "5PriDOuwEbmp"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.summarize()"
      ],
      "metadata": {
        "id": "Lf3pdwQ2Zch5"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Here we see that after the above steps, we will be training just ~ 200,000 parameters out of a 10+ M parameter model."
      ],
      "metadata": {
        "id": "JI6C_TYGGgyZ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Prepare NeMo's Experiment manager to handle checkpoint saving and logging for us\n",
        "from nemo.utils import exp_manager\n",
        "\n",
        "# Environment variable generally used for multi-node multi-gpu training.\n",
        "# In notebook environments, this flag is unnecessary and can cause logs of multiple training runs to overwrite each other.\n",
        "os.environ.pop('NEMO_EXPM_VERSION', None)\n",
        "\n",
        "exp_config = exp_manager.ExpManagerConfig(\n",
        "    exp_dir=f'experiments/',\n",
        "    name=f\"ASR-Adapters\",\n",
        "    checkpoint_callback_params=exp_manager.CallbackParams(\n",
        "        monitor=\"val_wer\",\n",
        "        mode=\"min\",\n",
        "        always_save_nemo=True,\n",
        "        save_best_model=True,\n",
        "    ),\n",
        ")\n",
        "\n",
        "exp_config = OmegaConf.structured(exp_config)\n",
        "\n",
        "logdir = exp_manager.exp_manager(trainer, exp_config)"
      ],
      "metadata": {
        "id": "w9ciIw-2bSHq"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Finally, train the adapters\n",
        "trainer.fit(model)"
      ],
      "metadata": {
        "id": "cY2TJod3ZfyE"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "After training, save the final checkpoint to a nemo file to evaluate. We also save just the adapter module itself, as that is much smaller than the size of the full model."
      ],
      "metadata": {
        "id": "A82ylXSZuL1T"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.save_to(\"/content/adapted_model.nemo\")"
      ],
      "metadata": {
        "id": "7tDdE9lZbvhJ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "model.save_adapters('/content/adapter_modules.pt')"
      ],
      "metadata": {
        "id": "L9yO-M-oL3Cy"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Evaluate the adapted model\n",
        "\n",
        "Now that we have finished the adaptation step and saved a trained NeMo file, we can evaluate the accuracy of our adapted model on the test set of AN4."
      ],
      "metadata": {
        "id": "Ak9v58RmdNJT"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Evaluate the adapter-enabled model"
      ],
      "metadata": {
        "id": "r-rjNJAvuZxu"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!python scripts/speech_to_text_eval.py \\\n",
        "  model_path=\"/content/adapted_model.nemo\" \\\n",
        "  dataset_manifest=$TEST_MANIFEST \\\n",
        "  output_filename=\"/content/adapted_predictions.json\" \\\n",
        "  batch_size=32 \\\n",
        "  use_cer=False"
      ],
      "metadata": {
        "id": "_Ps6_45mdJpM"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "We could significantly improve the accuracy of this model on the AN4 dataset with a very short training schedule with a small number of parameters. \n",
        "\n",
        "**Note**: Since AN4 is a relatively simple dataset, the gains are very large in this example. We generally observe more modest improvements with such short training schedules on realistic datasets (but gains of this range are easily attainable with more data or precise training schedules to avoid overfitting)."
      ],
      "metadata": {
        "id": "MegsAIcQG5MJ"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "Let us compare the adapted model's predictions below - "
      ],
      "metadata": {
        "id": "T6c_p530wMwG"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"Original\")\n",
        "!head -n 5 /content/unadapted_predictions.json\n",
        "print(\"Adapted\")\n",
        "!head -n 5 /content/adapted_predictions.json"
      ],
      "metadata": {
        "id": "vlK3PdMhtlv1"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Evaluate the adapter-disabled model\n",
        "\n",
        "Now, let us disable the adapters and recover the original performance of the model. We do this as a sanity test, to check that indeed the \"base\" model is still intact, even if adapter training has occurred."
      ],
      "metadata": {
        "id": "CCkH10jqd4q1"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.set_enabled_adapters(enabled=False)\n",
        "model.save_to(\"/content/adapter_disabled_model.nemo\")"
      ],
      "metadata": {
        "id": "1R6wHGgRdRKX"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "!python scripts/speech_to_text_eval.py \\\n",
        "  model_path=\"/content/adapter_disabled_model.nemo\" \\\n",
        "  dataset_manifest=$TEST_MANIFEST \\\n",
        "  output_filename=\"/content/adapter_disabled_predictions.json\" \\\n",
        "  batch_size=32 \\\n",
        "  use_cer=False"
      ],
      "metadata": {
        "id": "IhGLtRwdeGRf"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# [EXTRA] Check that accuracy can be recovered after adaptation\n",
        "\n",
        "This is a more explicit test than simply checking the WER above - here we do sample by sample check to ensure that predicted text remains the same."
      ],
      "metadata": {
        "id": "GGKgsW5gvAuf"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "original_transcripts = read_manifest('/content/unadapted_predictions.json')\n",
        "adapter_disabled_transcripts = read_manifest('/content/adapter_disabled_predictions.json')\n",
        "\n",
        "for orig, new in zip(original_transcripts, adapter_disabled_transcripts):\n",
        "  match = orig['pred_text'] == new['pred_text']\n",
        "  if not match:\n",
        "    print(\"Sample did not match after disabling adapter !\")\n",
        "    print(\"Original = \", orig['pred_text'])\n",
        "    print(\"Adapters disabled = \", new['pred_text']) \n",
        "    print()"
      ],
      "metadata": {
        "id": "YFKN7QYuvBzP"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# [EXTRA] Add as many adapters as needed\n",
        "\n",
        "Now that we have showcased how to utilize adapters for domain adaptation, we can take this further and adapt even more datasets - as many as needed!\n",
        "\n",
        "There is no implicit restriction on how many adapters can be added, as shown below. Still, we do recommend freezing all adapters and training only one at a time to prevent cross-interaction between adapters."
      ],
      "metadata": {
        "id": "0CqpJGR6ecYW"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.add_adapter(name=\"AN4-v2\", cfg=adapter_cfg)"
      ],
      "metadata": {
        "id": "13vZHFFEeK_g"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "model.set_enabled_adapters(enabled=False)\n",
        "model.set_enabled_adapters(name='AN4-v2', enabled=True)\n",
        "\n",
        "model.freeze()\n",
        "model.unfreeze_enabled_adapters()\n",
        "\n",
        "model.summarize()"
      ],
      "metadata": {
        "id": "iOrJ72SUelp6"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Further reading\n",
        "\n",
        "For efficient scripts to add, train, and evaluate adapter augmented models, please refer to the [Adapters example section](https://github.com/NVIDIA/NeMo/tree/main/examples/asr/asr_adapters).\n",
        "\n",
        "Please follow the following articles that discuss the use of adapters in ASR - \n",
        "- [Exploiting Adapters for Cross-lingual Low-resource Speech Recognition](https://arxiv.org/abs/2105.11905)\n",
        "- [Efficient Adapter Transfer of Self-Supervised Speech Models for Automatic Speech Recognition](https://arxiv.org/abs/2202.03218)\n"
      ],
      "metadata": {
        "id": "EIli6c_OvKDH"
      }
    }
  ]
}
